<template>
    <div class="content">
        <el-dialog :visible.sync="addClassMain.dialogFormVisible" title="添加班级" size="small" :before-close="handleClose">
            <div v-loading = "upLoading">
              <el-form ref="ruleForm" :model="ruleForm" label-width="90px">
                <el-form-item label-width="0" label="">
                    <span class="title">学校信息</span>
                </el-form-item>
                <div>
                    <el-row :gutter="21">
                        <el-col :span="8">
                            <el-form-item label="所在地区" prop="provinceId" :rules="rulesSelet">
                                <province v-model="ruleForm.provinceId" @change="changeProvice"></province>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label=" " prop="cityId" :rules="rulesSeletcity">
                                <city v-model="ruleForm.cityId" :province="ruleForm.provinceId" @change="changeCityId"></city>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label=" " prop="areaId" :rules="rulesSeletarea">
                                <region v-model="ruleForm.areaId" :city="ruleForm.cityId" @change="changeArea"></region>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="21">
                        <el-col :span="8">
                            <el-form-item label="学校名称" prop="schoolName" :rules="name">
                                <!-- <el-select v-model="ruleForm.schoolName" filterable clearable remote reserve-keyword placeholder="请输入学校名称" :remote-method="remoteMethod" :loading="loading" style="width:100%" @change="queryAllGrade">
                                    <el-option v-for="item in schoolList" :key="item.schoolId" :label="item.schoolName" :value="item.schoolId">
                                    </el-option>
                                </el-select> -->
                                <el-autocomplete v-model="ruleForm.schoolName" :fetch-suggestions="remoteMethod"
                                 :trigger-on-focus="true" placeholder="请输入关键词" @select="queryAllGrade" style="width:100%"></el-autocomplete>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
                <el-form-item label-width="0" label="">
                    <span class="title">班级信息</span>
                </el-form-item>
                <div>
                    <el-row :gutter="21">
                        <el-col :span="8">
                            <el-form-item v-if="schoolType === '0'" label="年级" prop="classGrade" :rules="rulesSelet">
                                <el-select v-model="ruleForm.classGrade" placeholder="请选择添加的班级" style="width:100%;" @change="queryAllClass( ruleForm.classGrade )">
                                    <el-option v-for="item in gradeList" :key="item.gradeId" :label="item.gradeName" :value="item.gradeId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="班级数量" prop="classNum" :rules="nameClassNum">
                              <el-popover placement="top-start" trigger="focus" content="请输入大于0小于10的整数">
                                <el-input slot="reference" :maxlength="2" v-model="ruleForm.classNum" placeholder="请输入小于等于10的整数"></el-input>
                              </el-popover>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
                <el-form-item label-width="0" label="">
                </el-form-item>
            </el-form>
            <footer>
                <el-button @click="cancel">取消</el-button>
                <el-button @click="add('ruleForm',$event)" type="primary">确认</el-button>
            </footer>
          </div>

        </el-dialog>
    </div>
</template>
<script>
import { addClassInfo, getSchoolList, getClass, getGrade } from "api/classAll";
import province from "components/CascadeRegion/province";
import city from "components/CascadeRegion/city";
import region from "components/CascadeRegion/region";
export default {
  name: "addClassSchool",
  components: { province, city, region },
  props: {
    addClassMain: {
      type: Object,
      required: true
    }
  },
  created() {},
  data() {
    return {
      upLoading: false,
      gradeList: [],
      autoFill: false,
      ruleForm: {
        schoolId: "",
        provinceId: "",
        cityId: "",
        areaId: "",
        schoolName: "",
        classGrade: "",
        classNum: ""
      },
      loading: false,
      schoolList: [],
      //是否培训和普通学校  1 0
      schoolType: "0",
      rulesSelet: {
        validator: (rule, value, callback) => {
          if (!this.provinceId && !value) {
            callback(new Error("请选择"));
          } else {
            callback();
          }
        },
        trigger: "change"
        // required: true, message: "请选择", trigger: "change"
      },
      rulesSeletcity: {
        validator: (rule, value, callback) => {
          if (!this.ruleForm.cityId && !value) {
            callback(new Error("请选择"));
          } else {
            callback();
          }
        },
        trigger: "change"
      },
      rulesSeletarea: {
        validator: (rule, value, callback) => {
          if (!this.ruleForm.areaId && !value) {
            callback(new Error("请选择"));
          } else {
            callback();
          }
        },
        trigger: "change"
      },
      name: { required: true, message: "请输入学校名称", trigger: "blur" },
      nameClassNum: [
        { message: "请输入班级数量", required: true },
        {
          message: "每次最多添加10个班",
          trigger: "blur",
          pattern: /^([1-9]|10)$/
        }
      ]
    };
  },
  methods: {
    //更改省市区学校名称清空
    changeProvice(val) {
      if (this.autoFill) return;
      this.ruleForm.schoolName = "";
      this.ruleForm.cityId = "";
    },
    changeCityId(val) {
      if (this.autoFill) return;
    },
    changeArea(val) {
      console.log(this.schoolList);
      if (this.autoFill) return;
      // this.ruleForm.schoolName = "";
      this.schoolList.forEach(item => {
        if (this.ruleForm.schoolName == item.value) {
          if (item.areaId !== val) {
            this.ruleForm.schoolName = "";
          }
        }
      });
      // if (!val) {
      //   this.ruleForm.schoolName = "";
      // }
    },
    remoteMethod(query, cb) {
      // this.loading = true;
      // if (query) {
      //   getSchoolList(
      //     query,
      //     !this.ruleForm.provinceId ? null : this.ruleForm.provinceId,
      //     !this.ruleForm.cityId ? null : this.ruleForm.cityId,
      //     !this.ruleForm.areaId ? null : this.ruleForm.areaId
      //   ).then(response => {
      //     this.loading = false;
      //     this.schoolList = response.data.content;
      //   });
      // } else {
      //   this.schoolList = [];
      //   this.ruleForm.schoolName = "";
      //   return;
      // }

      //
      if (this.ruleForm.schoolName != query && this.ruleForm.schoolName != "") {
        this.queryAllGrade("");
      }
      if (query) {
        getSchoolList(
          query,
          !this.ruleForm.provinceId ? null : this.ruleForm.provinceId,
          !this.ruleForm.cityId ? null : this.ruleForm.cityId,
          !this.ruleForm.areaId ? null : this.ruleForm.areaId
        )
          .then(response => {
            this.schoolList = response.data.content;
          })
          .then(() => {
            let results = this.schoolList.filter(this.createStateFilter(query));
            clearTimeout(this.timeout);
            this.timeout = setTimeout(() => {
              cb(results);
            }, 200 * Math.random());
          });
      } else {
        this.schoolList = [];
        this.ruleForm.schoolName = "";
        cb([]);
        return;
      }
    },
    createStateFilter(query) {
      return state => {
        state.value = state.schoolName;
        return state.value.toLowerCase().includes(query.toLowerCase());
      };
    },

    //判断是否普通学校/培训学校
    judgmentSta(val) {
      this.schoolList.forEach(item => {
        if (val === item.schoolId) {
          this.schoolType = item.schoolType;
        }
      });
    },

    // 年级列表
    queryAllGrade(val) {
      //判断用户是否确认选择
      this.ruleForm.schoolId = val.schoolId;
      if (val.schoolId) {
        this.judgmentSta(val.schoolId);
        //填充省市区
        let school = this.schoolList.find(s => s.schoolId == val.schoolId);
        this.ruleForm.provinceId = school.provinceId;
        this.ruleForm.cityId = school.cityId;
        this.ruleForm.areaId = school.areaId;
      }

      this.autoFill = true;
      this.$nextTick(() => {
        this.autoFill = false;
      });
      this.getGradeName = "";
      this.newSchoolId = val.schoolId;
      if (val.schoolId) {
        getGrade(!val.schoolId ? null : val.schoolId).then(response => {
          this.gradeList = response.data.content;
        });
      }
    },
    // 班级列表
    queryAllClass(gradeId) {
      this.classIdIn = gradeId;
      getClass(
        !this.newSchoolId ? null : this.newSchoolId,
        !gradeId ? null : gradeId
      ).then(response => {
        this.classList = response.data.content;
      });
    },
    handleClose() {
      this.$refs.ruleForm.resetFields();
      this.addClassMain.dialogFormVisible = false;
    },
    add(ruleForm,event) {
      if(event.clientX == 0) return;
      this.$refs[ruleForm].validate(valid => {
        if (!valid) {
          return false;
        } else {
          this.upLoading = true;
          // this.$message("已经添加成功，请稍等更新~");
          // this.loading = false;
          // this.addClassMain.dialogFormVisible = false;
          let schoolId = this.ruleForm.schoolId;
          addClassInfo(
            "10",
            this.ruleForm.provinceId,
            this.ruleForm.cityId,
            this.ruleForm.areaId,
            schoolId,
            this.ruleForm.classGrade,
            this.ruleForm.classNum + ""
          )
            .then(data => {
              this.upLoading = false;
              // this.addClassMain.dialogFormVisible = false;
              //给父组件传值
              this.$message({
                message: "添加成功！",
                type: "success"
              });
              if (this.addClassMain.provinceId || this.ruleForm.provinceId) this.$emit("addClassState", true);
              // this.$store.dispatch('UpdateCache');
              this.addClassMain.dialogFormVisible = false;
            })
            .catch(Error => {
              this.upLoading = false;
              this.$message(Error);
            });
        }
      });
    },
    cancel() {
      this.addClassMain.dialogFormVisible = false;
    }
  }
};
</script>
<style lang="scss" scoped>
.title {
  display: block;
  text-align: left;
  margin-left: 20px;
  font-size: 14px;
  margin-bottom: 18px;
  color: #333;
  position: relative;
  &::after {
    position: absolute;
    width: 4px;
    height: 14px;
    background: #ff5e2c;
    left: -15px;
    top: 10px;
    content: "";
  }
}

footer {
  text-align: center;
}
</style>
